﻿using BackData;
using Domain.DTOs.RBAC;
using Domain.RBAC;
using Infratructure;
using MD5Hash;
using MediatR;
using Team.API.Applocation.Command.Users;

namespace Team.API.Applocation.Handler.Users
{
    public class UpdateUserPassHandler : IRequestHandler<UpdateUserPassCommand, APIResult<int>>
    {
        private readonly IRepository<Usermodel> userRepository;

        private readonly IRepository<Rolemodel> roleRepository;

        private readonly IRepository<Departmentmodel> depRepository;

        public UpdateUserPassHandler(IRepository<Usermodel> userRepository, IRepository<Rolemodel> roleRepository, IRepository<Departmentmodel> depRepository)
        {
            this.userRepository = userRepository;
            this.roleRepository = roleRepository;
            this.depRepository = depRepository;
        }

        public async Task<APIResult<int>> Handle(UpdateUserPassCommand request, CancellationToken cancellationToken)
        {
            var user = await userRepository.GetByIdAsync(request.Id);
            var pass = request.Pass.GetMD5WithSalt(user.Salt);
            if(user.Password != pass)
            {
                return APIResult<int>.Faile("原密码不正确");
            }
            user.Password = request.NewPass.GetMD5WithSalt(user.Salt);

            int i = await userRepository.UpdateAsync(user);
            if (i <= 0)
            {
                return APIResult<int>.Faile("密码修改失败");
            }
            else
            {
                return APIResult<int>.Ok("密码修改成功", i);
            }
        }
    }
}
